using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf;
using CPlatePrintSys.Annotation.Events;
using Prism.Events;

namespace CPlatePrintSys.Annotation.Converters
{
    /// <summary>
    /// 相机同步管理器
    /// 负责协调两个视图之间的相机同步操作
    /// </summary>
    public class CameraSyncManager
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly Dictionary<string, HelixViewport3D> _viewports;
        private readonly Dictionary<string, long> _lastSyncTimestamps;
        private readonly Dictionary<string, int> _syncLoopCounts; // 同步循环计数器
        private readonly Dictionary<string, long> _lastLoopResetTimestamps; // 最后循环重置时间戳
        private string _currentActiveViewport; // 当前活跃的视口ID
        private readonly object _syncLock = new object();
        
        // 配置参数
        private const int SYNC_THROTTLE_MS = 100; // 同步节流时间（毫秒）- 增加节流时间，减少对滚轮操作的干扰
        private const int MAX_SYNC_QUEUE_SIZE = 100; // 最大同步队列大小
        private const int MAX_SYNC_LOOP_COUNT = 3; // 最大同步循环次数
        private const int LOOP_COUNT_RESET_INTERVAL_MS = 1000; // 循环计数重置间隔（毫秒）
        
        // 同步队列
        private readonly Queue<CameraSyncEventArgs> _syncQueue;
        private bool _isProcessingQueue = false;

        public CameraSyncManager(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator));
            _viewports = new Dictionary<string, HelixViewport3D>();
            _lastSyncTimestamps = new Dictionary<string, long>();
            _syncLoopCounts = new Dictionary<string, int>();
            _lastLoopResetTimestamps = new Dictionary<string, long>();
            _syncQueue = new Queue<CameraSyncEventArgs>();
            
            //Debug.WriteLine("CameraSyncManager 构造函数开始");      
            try
            {
                // 订阅相机同步事件
                var cameraSyncEvent = _eventAggregator.GetEvent<CameraSyncEvent>();
                //Debug.WriteLine($"相机同步事件获取成功: {cameraSyncEvent != null}");
                
                cameraSyncEvent.Subscribe(OnCameraSyncRequest, ThreadOption.UIThread);
                //Debug.WriteLine("相机同步事件订阅成功");
                
                //Debug.WriteLine("CameraSyncManager 初始化完成");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"CameraSyncManager 初始化失败: {ex.Message}");
                Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 注册视口
        /// </summary>
        /// <param name="controlId">控件ID</param>
        /// <param name="viewport">视口对象</param>
        public void RegisterViewport(string controlId, HelixViewport3D viewport)
        {
            if (string.IsNullOrEmpty(controlId) || viewport == null)
            {
                Debug.WriteLine($"视口注册失败: controlId={controlId}, viewport={viewport}");
                return;
            }

            lock (_syncLock)
            {
                _viewports[controlId] = viewport;
                _lastSyncTimestamps[controlId] = 0;
                _syncLoopCounts[controlId] = 0; // 重置循环计数
                _lastLoopResetTimestamps[controlId] = DateTime.Now.Ticks / 10000; // 设置重置时间戳
                
                // 设置第一个注册的视口为默认活跃视图
                if (string.IsNullOrEmpty(_currentActiveViewport))
                {
                    _currentActiveViewport = controlId;
                    //Debug.WriteLine($"设置默认活跃视口: {controlId}");
                }
            }
        }

        /// <summary>
        /// 设置当前活跃的视口
        /// </summary>
        /// <param name="controlId">活跃视口ID</param>
        public void SetCurrentActiveViewport(string controlId)
        {
            if (string.IsNullOrEmpty(controlId))
                return;

            lock (_syncLock)
            {
                if (_viewports.ContainsKey(controlId))
                {
                    var oldActive = _currentActiveViewport;
                    _currentActiveViewport = controlId;
                    //Debug.WriteLine($"设置当前活跃视口: {oldActive} -> {_currentActiveViewport}");
                }
                else
                {
                    Debug.WriteLine($"尝试设置未注册的视口为活跃: {controlId}");
                }
            }
        }

        /// <summary>
        /// 获取当前活跃的视口ID
        /// </summary>
        /// <returns>当前活跃视口ID</returns>
        public string GetCurrentActiveViewport()
        {
            lock (_syncLock)
            {
                return _currentActiveViewport;
            }
        }

        /// <summary>
        /// 注销视口
        /// </summary>
        /// <param name="controlId">控件ID</param>
        public void UnregisterViewport(string controlId)
        {
            if (string.IsNullOrEmpty(controlId))
                return;

            lock (_syncLock)
            {
                _viewports.Remove(controlId);
                _lastSyncTimestamps.Remove(controlId);
                _syncLoopCounts.Remove(controlId); // 清理循环计数
                _lastLoopResetTimestamps.Remove(controlId); // 清理重置时间戳
                
                //Debug.WriteLine($"Viewport unregistered: {controlId}");
            }
        }

        /// <summary>
        /// 发布相机同步事件
        /// </summary>
        /// <param name="sourceControlId">源控件ID</param>
        /// <param name="operation">同步操作类型</param>
        /// <param name="camera">相机对象</param>
        public void PublishCameraSync(string sourceControlId, CameraSyncOperation operation, ProjectionCamera camera)
        {
            if (string.IsNullOrEmpty(sourceControlId) || camera == null)
                return;

            // 检查源控件是否为当前活跃视图
            if (!IsCurrentActiveViewport(sourceControlId))
            {
                //Debug.WriteLine($"跳过同步：{sourceControlId} 不是当前活跃视图，当前活跃视图: {_currentActiveViewport}");
                return;
            }

            // 节流检查
            if (!ShouldSync(sourceControlId))
                return;

            try
            {
                var targetControlId = GetTargetControlId(sourceControlId);
                //Debug.WriteLine($"=== 开始发布相机同步 ===");
                //Debug.WriteLine($"源控件ID: {sourceControlId} (当前活跃视图)");
                //Debug.WriteLine($"目标控件ID: {targetControlId}");
                //Debug.WriteLine($"操作类型: {operation}");
                //Debug.WriteLine($"同步方向: {sourceControlId} -> {targetControlId}");
                
                var args = CreateCameraSyncEventArgs(sourceControlId, operation, camera);
                
                // 直接执行同步，不通过队列
                //Debug.WriteLine($"直接执行相机同步，跳过队列");
                ExecuteCameraSync(args);
                
                // 同时发布事件（用于其他可能的监听器）
                //Debug.WriteLine($"发布相机同步事件到事件系统");
                _eventAggregator.GetEvent<CameraSyncEvent>().Publish(args);
                
                //Debug.WriteLine($"=== 相机同步发布完成 ===");
                //Debug.WriteLine($"操作: {operation} 从 {sourceControlId} 到 {targetControlId}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"发布相机同步失败: {ex.Message}");
                Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 处理相机同步请求
        /// </summary>
        /// <param name="args">同步事件参数</param>
        private void OnCameraSyncRequest(CameraSyncEventArgs args)
        {
            try
            {
                //Debug.WriteLine($"收到相机同步请求: {args.SourceControlId} -> {args.TargetControlId}");
                //Debug.WriteLine($"操作类型: {args.Operation}");
                //Debug.WriteLine($"是否为初始同步: {args.IsInitialSync}");
                
                // 对于初始同步事件，跳过节流检查
                if (args.IsInitialSync)
                {
                    //Debug.WriteLine("初始同步事件，跳过节流检查，直接执行同步");
                    if (ValidateSyncRequest(args))
                    {
                        ExecuteCameraSync(args);
                    }
                    else
                    {
                        //Debug.WriteLine("初始同步事件验证失败");
                    }
                    return;
                }
                
                // 验证请求
                if (!ValidateSyncRequest(args))
                {
                    //Debug.WriteLine($"同步请求验证失败: {args.SourceControlId} -> {args.TargetControlId}");
                    return;
                }

                // 检查节流
                if (!ShouldSync(args.TargetControlId))
                {
                    //Debug.WriteLine($"同步请求被节流: {args.SourceControlId} -> {args.TargetControlId}");
                    return;
                }

                // 添加到同步队列
                lock (_syncLock)
                {
                    if (_syncQueue.Count < MAX_SYNC_QUEUE_SIZE)
                    {
                        _syncQueue.Enqueue(args);
                       // Debug.WriteLine($"同步请求已加入队列，当前队列大小: {_syncQueue.Count}");
                        
                        if (!_isProcessingQueue)
                        {
                            ProcessSyncQueue();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"处理相机同步请求失败: {ex.Message}");
                Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 验证同步请求
        /// </summary>
        private bool ValidateSyncRequest(CameraSyncEventArgs args)
        {
            if (string.IsNullOrEmpty(args.SourceControlId) || 
                string.IsNullOrEmpty(args.TargetControlId) ||
                args.SourceControlId == args.TargetControlId)
            {
                return false;
            }

            // 检查目标视口是否存在
            lock (_syncLock)
            {
                return _viewports.ContainsKey(args.TargetControlId);
            }
        }

        /// <summary>
        /// 执行相机同步
        /// </summary>
        private void ExecuteCameraSync(CameraSyncEventArgs args)
        {
            //Debug.WriteLine($"=== 开始执行相机同步 ===");
            //Debug.WriteLine($"同步方向: {args.SourceControlId} -> {args.TargetControlId}");
            //Debug.WriteLine($"操作类型: {args.Operation}");
            //Debug.WriteLine($"源控件ID: {args.SourceControlId}");
            //Debug.WriteLine($"目标控件ID: {args.TargetControlId}");
            //Debug.WriteLine($"是否为初始同步: {args.IsInitialSync}");
            
            lock (_syncLock)
            {
                //Debug.WriteLine($"当前已注册视口数量: {_viewports.Count}");
                //Debug.WriteLine($"已注册视口列表: {string.Join(", ", _viewports.Keys)}");
                
                if (!_viewports.TryGetValue(args.TargetControlId, out var targetViewport))
                {
                    //Debug.WriteLine($"目标视口未找到: {args.TargetControlId}");
                    //Debug.WriteLine($"可用视口: {string.Join(", ", _viewports.Keys)}");
                    return;
                }

                //Debug.WriteLine($"目标视口找到: {args.TargetControlId}");
                
                var targetCamera = targetViewport.Camera as ProjectionCamera;
                if (targetCamera == null)
                {
                    //Debug.WriteLine($"目标相机为空或不是ProjectionCamera: {args.TargetControlId}");
                    //Debug.WriteLine($"相机类型: {targetViewport.Camera?.GetType().Name ?? "null"}");
                    return;
                }

                //Debug.WriteLine($"目标相机类型: {targetCamera.GetType().Name}");
                //Debug.WriteLine($"目标相机当前位置: {targetCamera.Position}");
                //Debug.WriteLine($"目标相机当前方向: {targetCamera.LookDirection}");

                try
                {
                    // 对于初始同步，跳过循环检测和节流限制
                    if (!args.IsInitialSync)
                    {
                        // 增加同步循环计数
                        IncrementSyncLoopCount(args.TargetControlId);
                    }
                    else
                    {
                        //Debug.WriteLine("初始同步事件，跳过循环检测和节流限制");
                    }
                    
                    //Debug.WriteLine($"开始同步相机: {args.Operation} 从 {args.SourceControlId} 到 {args.TargetControlId}");

                    // 根据操作类型执行同步
                    switch (args.Operation)
                    {
                        case CameraSyncOperation.Position:
                            SyncCameraPosition(targetCamera, args);
                            break;
                        case CameraSyncOperation.Direction:
                            SyncCameraDirection(targetCamera, args);
                            break;
                        case CameraSyncOperation.Zoom:
                            SyncCameraZoom(targetCamera, args);
                            break;
                        case CameraSyncOperation.Full:
                            SyncCameraFull(targetCamera, args);
                            break;
                        default:
                            // 对于初始同步，如果没有指定操作类型，执行完整同步
                            if (args.IsInitialSync)
                            {
                                //Debug.WriteLine("初始同步：执行完整相机同步");
                                SyncCameraFull(targetCamera, args);
                            }
                            break;
                    }

                    // 更新最后同步时间戳
                    _lastSyncTimestamps[args.TargetControlId] = args.Timestamp;
                    
                    //Debug.WriteLine($"相机同步完成: {args.Operation} 从 {args.SourceControlId} 到 {args.TargetControlId}");
                    //Debug.WriteLine($"同步后相机位置: {targetCamera.Position}");
                    //Debug.WriteLine($"同步后相机方向: {targetCamera.LookDirection}");
                    //Debug.WriteLine($"=== 相机同步执行完成 ===");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"相机同步执行失败 {args.TargetControlId}: {ex.Message}");
                    Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
                }
            }
        }

        /// <summary>
        /// 同步相机位置
        /// </summary>
        private void SyncCameraPosition(ProjectionCamera targetCamera, CameraSyncEventArgs args)
        {
            try
            {
                if (args.Position.HasValue)
                {
                    var oldPosition = targetCamera.Position;
                    targetCamera.Position = args.Position.Value;
                    //Debug.WriteLine($"相机位置同步: {oldPosition} -> {targetCamera.Position}");
                }
                else
                {
                   // Debug.WriteLine($"相机位置同步跳过: 位置参数为空");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"同步相机位置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步相机方向
        /// </summary>
        private void SyncCameraDirection(ProjectionCamera targetCamera, CameraSyncEventArgs args)
        {
            try
            {
                if (args.LookDirection.HasValue)
                {
                    var oldLookDirection = targetCamera.LookDirection;
                    targetCamera.LookDirection = args.LookDirection.Value;
                    //Debug.WriteLine($"相机观察方向同步: {oldLookDirection} -> {targetCamera.LookDirection}");
                }
                
                if (args.UpDirection.HasValue)
                {
                    var oldUpDirection = targetCamera.UpDirection;
                    targetCamera.UpDirection = args.UpDirection.Value;
                    //Debug.WriteLine($"相机向上方向同步: {oldUpDirection} -> {targetCamera.UpDirection}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"同步相机方向失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 同步相机缩放
        /// </summary>
        private void SyncCameraZoom(ProjectionCamera targetCamera, CameraSyncEventArgs args)
        {
            try
            {
                Debug.WriteLine($"=== 开始同步相机缩放 ===");
                Debug.WriteLine($"目标相机类型: {targetCamera.GetType().Name}");
                Debug.WriteLine($"源相机视野角度: {args.FieldOfView}");
                Debug.WriteLine($"源相机宽度: {args.Width}");

                if (targetCamera is PerspectiveCamera perspectiveCamera && args.FieldOfView.HasValue)
                {
                    var oldFieldOfView = perspectiveCamera.FieldOfView;
                    perspectiveCamera.FieldOfView = args.FieldOfView.Value;
                    Debug.WriteLine($"透视相机视野角度同步: {oldFieldOfView:F2} -> {perspectiveCamera.FieldOfView:F2}");
                    
                    // 确保缩放比的一致性
                    if (Math.Abs(oldFieldOfView - perspectiveCamera.FieldOfView) > 0.01)
                    {
                        Debug.WriteLine($"缩放同步成功: 视野角度从 {oldFieldOfView:F2}° 调整为 {perspectiveCamera.FieldOfView:F2}°");
                    }
                }
                else if (targetCamera is OrthographicCamera orthographicCamera && args.Width.HasValue)
                {
                    var oldWidth = orthographicCamera.Width;
                    orthographicCamera.Width = args.Width.Value;
                    Debug.WriteLine($"正交相机宽度同步: {oldWidth:F2} -> {orthographicCamera.Width:F2}");
                    
                    // 确保缩放比的一致性
                    if (Math.Abs(oldWidth - orthographicCamera.Width) > 0.01)
                    {
                        Debug.WriteLine($"缩放同步成功: 宽度从 {oldWidth:F2} 调整为 {orthographicCamera.Width:F2}");
                    }
                }
                else
                {
                    Debug.WriteLine($"相机类型不匹配或缺少缩放参数");
                    Debug.WriteLine($"目标相机类型: {targetCamera.GetType().Name}");
                    Debug.WriteLine($"源相机类型: {(args.FieldOfView.HasValue ? "Perspective" : "Orthographic")}");
                }
                
                Debug.WriteLine($"=== 相机缩放同步完成 ===");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"同步相机缩放失败: {ex.Message}");
                Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 完整相机同步
        /// </summary>
        private void SyncCameraFull(ProjectionCamera targetCamera, CameraSyncEventArgs args)
        {
            try
            {
                //Debug.WriteLine($"=== 开始完整相机同步 ===");
                //Debug.WriteLine($"是否为初始同步: {args.IsInitialSync}");
                //Debug.WriteLine($"目标控件ID: {args.TargetControlId}");
                //Debug.WriteLine($"同步前相机状态:");
                //Debug.WriteLine($"  位置: {targetCamera.Position}");
                //Debug.WriteLine($"  观察方向: {targetCamera.LookDirection}");
                //Debug.WriteLine($"  向上方向: {targetCamera.UpDirection}");
                
                if (args.IsInitialSync)
                {
                    //Debug.WriteLine("初始同步：执行完整的相机状态同步");
                }
                
                // 同步相机位置
                SyncCameraPosition(targetCamera, args);
                
                // 同步相机方向
                SyncCameraDirection(targetCamera, args);
                
                // 同步相机缩放
                SyncCameraZoom(targetCamera, args);
                
                //Debug.WriteLine($"同步后相机状态:");
                //Debug.WriteLine($"  位置: {targetCamera.Position}");
                //Debug.WriteLine($"  观察方向: {targetCamera.LookDirection}");
                //Debug.WriteLine($"  向上方向: {targetCamera.UpDirection}");
                //Debug.WriteLine($"=== 完整相机同步完成 ===");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"完整相机同步失败: {ex.Message}");
                Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 创建相机同步事件参数
        /// </summary>
        private CameraSyncEventArgs CreateCameraSyncEventArgs(string sourceControlId, CameraSyncOperation operation, ProjectionCamera camera)
        {
            try
            {
                var args = new CameraSyncEventArgs
                {
                    SourceControlId = sourceControlId,
                    TargetControlId = GetTargetControlId(sourceControlId),
                    Operation = operation,
                    Position = camera.Position,
                    LookDirection = camera.LookDirection,
                    UpDirection = camera.UpDirection
                };

                // 根据相机类型设置特定属性
                if (camera is PerspectiveCamera perspectiveCamera)
                {
                    args.FieldOfView = perspectiveCamera.FieldOfView;
                    //Debug.WriteLine($"创建透视相机同步参数: FieldOfView={perspectiveCamera.FieldOfView}");
                }
                else if (camera is OrthographicCamera orthographicCamera)
                {
                    args.Width = orthographicCamera.Width;
                    //Debug.WriteLine($"创建正交相机同步参数: Width={orthographicCamera.Width}");
                }
                else
                {
                    //Debug.WriteLine($"未知相机类型: {camera.GetType().Name}");
                }

                //Debug.WriteLine($"相机同步参数创建完成:");
                //Debug.WriteLine($"  位置: {args.Position}");
                //Debug.WriteLine($"  观察方向: {args.LookDirection}");
                //Debug.WriteLine($"  向上方向: {args.UpDirection}");
                //Debug.WriteLine($"  视野角度: {args.FieldOfView}");
                //Debug.WriteLine($"  宽度: {args.Width}");

                return args;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"创建相机同步参数失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 获取目标控件ID
        /// </summary>
        private string GetTargetControlId(string sourceControlId)
        {
            return sourceControlId == "normal" ? "mirror" : "normal";
        }

        /// <summary>
        /// 检查指定控件是否为当前活跃视图
        /// </summary>
        /// <param name="controlId">控件ID</param>
        /// <returns>是否为当前活跃视图</returns>
        private bool IsCurrentActiveViewport(string controlId)
        {
            lock (_syncLock)
            {
                if (string.IsNullOrEmpty(_currentActiveViewport))
                {
                    // 如果没有设置活跃视图，默认允许同步
                   // Debug.WriteLine($"未设置活跃视图，允许同步: {controlId}");
                    return true;
                }

                var isActive = _currentActiveViewport == controlId;
                if (!isActive)
                {
                    //Debug.WriteLine($"视图 {controlId} 不是当前活跃视图，当前活跃视图: {_currentActiveViewport}");
                }

                return isActive;
            }
        }

    
        /// <summary>
        /// 检查并重置循环计数
        /// </summary>
        private void CheckAndResetLoopCount(string controlId)
        {
            if (!_lastLoopResetTimestamps.TryGetValue(controlId, out var lastReset))
            {
                _lastLoopResetTimestamps[controlId] = DateTime.Now.Ticks / 10000;
                return;
            }

            var timeSinceLastReset = (DateTime.Now.Ticks / 10000) - lastReset;
            if (timeSinceLastReset >= LOOP_COUNT_RESET_INTERVAL_MS)
            {
                _syncLoopCounts[controlId] = 0;
                _lastLoopResetTimestamps[controlId] = DateTime.Now.Ticks / 10000;
                //Debug.WriteLine($"定时重置循环计数: {controlId}");
            }
        }

        /// <summary>
        /// 增加同步循环计数
        /// </summary>
        private void IncrementSyncLoopCount(string controlId)
        {
            lock (_syncLock)
            {
                if (!_syncLoopCounts.TryGetValue(controlId, out var loopCount))
                {
                    _syncLoopCounts[controlId] = 1;
                }
                else
                {
                    _syncLoopCounts[controlId] = loopCount + 1;
                }

               // Debug.WriteLine($"增加同步循环计数: {controlId} -> {_syncLoopCounts[controlId]}");
            }
        }

        /// <summary>
        /// 检查是否应该同步
        /// </summary>
        private bool ShouldSync(string controlId)
        {
            lock (_syncLock)
            {
                if (!_lastSyncTimestamps.TryGetValue(controlId, out var lastSync))
                    return true;

                var timeSinceLastSync = (DateTime.Now.Ticks / 10000) - lastSync;
                var shouldSync = timeSinceLastSync >= SYNC_THROTTLE_MS;
                
                if (!shouldSync)
                {
                   // Debug.WriteLine($"节流检查: {controlId} 距离上次同步 {timeSinceLastSync}ms < {SYNC_THROTTLE_MS}ms，跳过同步");
                }
                
                return shouldSync;
            }
        }

        /// <summary>
        /// 处理同步队列
        /// </summary>
        private async void ProcessSyncQueue()
        {
            if (_isProcessingQueue)
                return;

            _isProcessingQueue = true;

            try
            {
                while (true)
                {
                    CameraSyncEventArgs args;
                    
                    lock (_syncLock)
                    {
                        if (_syncQueue.Count == 0)
                            break;
                            
                        args = _syncQueue.Dequeue();
                    }

                    // 发布事件
                    _eventAggregator.GetEvent<CameraSyncEvent>().Publish(args);
                    
                    // 短暂延迟，避免阻塞UI
                    await System.Threading.Tasks.Task.Delay(1);
                }
            }
            finally
            {
                _isProcessingQueue = false;
            }
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        public void Dispose()
        {
            lock (_syncLock)
            {
                _viewports.Clear();
                _lastSyncTimestamps.Clear();
                _syncLoopCounts.Clear(); // 清理循环计数
                _lastLoopResetTimestamps.Clear(); // 清理重置时间戳
                _syncQueue.Clear();
            }
            
            Debug.WriteLine("CameraSyncManager disposed");
        }
    }
}
